<template>
  <div class="login-container">
    <el-header class="login-header">
      <el-image class="header-img" src="../../static/img/logo.jpg"></el-image>
    </el-header>
    <el-main class="login-main">
      <el-row style="width: 25%; margin: 0 auto">
        <el-col :span="24">
          <el-form label-position="'left'" ref="registerFrom" label-width="80px" :model="registerFrom" :rules="rules">
            <el-form-item label="用户名" prop="username">
              <el-input placeholder="请输入用户名" v-model="registerFrom.username" clearable></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input placeholder="请输入手机号码" v-model="registerFrom.phoneNumber" clearable>
                <template slot="append">
                  <el-button plain @click="sendYzm" v-if="!yzmDisabled">发送验证码</el-button>
                  <el-button :disabled="yzmDisabled" v-if="yzmDisabled" plain>{{countDown}}秒后重新发送</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="yzm">
              <el-input placeholder="请输入验证码" v-model="registerFrom.yzm" clearable></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="name">
              <el-input placeholder="请输入真实姓名" v-model="registerFrom.name" clearable></el-input>
            </el-form-item>
            <el-form-item label="身份证号" prop="idNumber">
              <el-input placeholder="请输入身份证号" v-model="registerFrom.idNumber" clearable></el-input>
            </el-form-item>
            <el-form-item label="输入密码" prop="pwd">
              <el-input type="password" placeholder="请输入密码" v-model="registerFrom.pwd" autocomplete="off" clearable
                        show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="ackPwd">
              <el-input type="password" placeholder="再次输入密码" v-model="registerFrom.ackPwd" autocomplete="off"
                        clearable
                        show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button class="register-btn-cls" @click="handleSubmit" :loading="logining">注 册</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-main>
    <el-footer>
      <ets-footer/>
    </el-footer>
  </div>
</template>

<script>
export default {
  name: 'Register',
  components: {},
  created () {

  },
  data () {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerFrom.ackPwd !== '') {
          this.$refs.registerFrom.validateField('ackPwd')
        }
        callback()
      }
    }
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerFrom.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    let validatePhoneNumber = (rule, value, callback) => {
      let phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
      if (phoneReg.test(value)) {
        callback()
        this.isFsyzm = true
      } else {
        callback(new Error('请输入正确的大陆手机号码！'))
        this.isFsyzm = false
      }
    }
    let validateUsernameUniq = (rule, value, callback) => {
      let _this = this
      if (value === '' || value === ' ') {
        callback()
        return
      }
      this.$axios({
        url: '/api/users/username/' + _this.registerFrom.username,
        method: 'get',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': _this.getToken()
        }
      }).then((response) => {
        if (response.data.code === 1) {
          if (response.data.data) {
            callback()
          } else {
            callback(new Error('用户名已存在'))
          }
        } else {
          _this.isTokenExpired(_this, response.data.msg)
          this.err(response.data.msg)
        }
      })
    }
    let validateIdNumber = (rule, value, callback) => {
      let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      let _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
      // 校验身份证：
      if (_IDRe18.test(value) || _IDre15.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的身份证号'))
      }
    }
    return {
      logining: false,
      isFsyzm: false,
      yzmDisabled: false, // 按钮是否可用
      countDown: 60, // 倒计时时间（单位：秒）
      registerFrom: {
        username: '',
        phoneNumber: '',
        yzm: '',
        pwd: '',
        ackPwd: '',
        idNumber: '',
        name: ''
      },
      rules: {
        username: [
          {validator: validateUsernameUniq, required: true, trigger: 'blur'}
        ],
        yzm: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ],
        pwd: [
          {validator: validatePass, required: true, trigger: 'blur'}
        ],
        ackPwd: [
          {validator: validatePass2, required: true, trigger: 'blur'}
        ],
        phoneNumber: [
          {validator: validatePhoneNumber, required: true, trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入身份证姓名', trigger: 'blur'}
        ],
        idNumber: [
          {validator: validateIdNumber, required: true, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    startCountDown () {
      this.yzmDisabled = true // 禁用按钮
      let timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--
        } else {
          clearInterval(timer)
          this.yzmDisabled = false // 启用按钮
          this.countDown = 60 // 重置倒计时时间
        }
      }, 1000)
    },
    sendYzm () {
      let _this = this
      if (this.isFsyzm) {
        _this.startCountDown()
        this.$axios({
          url: '/api/sms',
          method: 'post',
          data: JSON.stringify({
            phoneNumber: _this.registerFrom.phoneNumber
          }),
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'token': _this.getToken()
          }
        }).then((response) => {
          if (response.data.code === 1) {} else {
            _this.isTokenExpired(_this, response.data.msg)
            this.err(response.data.msg)
          }
        })
      } else {
        this.warn('请输入手机号码！')
      }
    },
    handleSubmit () {
      let _this = this
      // 发送注册
      // 密码、身份证号加密传输
      this.$refs.registerFrom.validate((valid) => {
        if (valid) {
          this.logining = true
          let iv = _this.randomIv(16)
          let pwdM = _this.encrypt(_this.registerFrom.ackPwd, iv)
          _this.registerFrom.pwd = pwdM
          _this.registerFrom.ackPwd = pwdM
          this.$axios({
            url: '/api/users',
            method: 'post',
            data: JSON.stringify({
              username: _this.registerFrom.username,
              phoneNumber: _this.registerFrom.phoneNumber,
              password: _this.registerFrom.ackPwd,
              name: _this.registerFrom.name,
              idNumber: _this.encrypt(_this.registerFrom.idNumber, iv),
              code: _this.registerFrom.yzm,
              iv: iv
            }),
            headers: {
              'Content-Type': 'application/json; charset=utf-8',
              'token': _this.getToken()
            }
          }).then((response) => {
            if (response.data.code === 1) {
              _this.logining = false
              _this.success('注册成功，请登录')
              _this.$router.push({
                path: '/login'
              })
            } else {
              _this.isTokenExpired(_this, response.data.msg)
              _this.err(response.data.msg)
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100%;
}

.login-header {
  margin-bottom: 40px;
}

.login-main {
  padding-top: 5%;
  height: 65%;
}

.header-img {
  position: absolute;
  left: 10%;
  top: 2%;
  width: 219px;
  height: 60px;
}

.register-btn-cls {
  width: 40%;
  background-color: var(--them-color);
  color: #FFFFFF;
  border: none;
  font-size: 20px;
}

</style>
